﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EasyMvc.Utility;

namespace EasyMvc.Web.Common
{
    public class PermissionHelper
    {
        /// <summary>
        /// 反序列化数据库里的json到实体
        /// </summary>
        /// <param name="permissionJson"></param>
        /// <returns></returns>
        public static Permission Parse(string permissionJson)
        {
            var permission = new Permission();

            if (!string.IsNullOrEmpty(permissionJson))
            {
                try
                {
                    permission = SerializationHelper.JsonDeserialize<Permission>(permissionJson);
                }
                catch
                {
                }
            }

            return permission;
        }

        /// <summary>
        /// 序列化实体到json提交到数据库
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        public static string ToJson(Permission permission)
        {
            return SerializationHelper.JsonSerialize<Permission>(permission);
        }
        
        /// <summary>
        /// 判断Controller或Action上是否有对应的权限Attribute
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="userContext"></param>
        /// <returns></returns>
        public static bool HasPermission(ActionExecutingContext filterContext, UserContext userContext)
        {
            var actionPermissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>();
            var controllerPermissionAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>();

            var viewPermissions = new HashSet<EnumViewPermission>();
            if (actionPermissionAttributes != null && actionPermissionAttributes.Count() > 0)
                actionPermissionAttributes.First().Allow.ToList().ForEach(p => viewPermissions.Add(p));
            if (controllerPermissionAttributes != null && controllerPermissionAttributes.Count() > 0)
                controllerPermissionAttributes.First().Allow.ToList().ForEach(p => viewPermissions.Add(p));

            bool hasPermission = true;
            foreach (var vp in viewPermissions)
            {
                if (!userContext.Permission.ViewPermissions.Contains(vp))
                {
                    hasPermission = false;
                    break;
                }
            }

            return hasPermission;
        }
    }
}